﻿#include "TCP_ServerMode.h"
#include <QDebug>

#define DEBUGinfo qDebug()

TCP_Server::TCP_Server()
{
    Server = new QTcpServer(this);
    MyClients.clear();
    connect(Server,&QTcpServer::newConnection,this,&TCP_Server::HasClientConnect);
}

TCP_Server::~TCP_Server()
{
    if(Server->isListening())
        Server->close();
    if(MyClients.size() != 0)
    {
        for(auto s : MyClients.values())
        {
            s->abort();
            s->deleteLater();
        }
        MyClients.clear();
    }
}
//开启监听
void TCP_Server::StartListen(QString ipAddress, quint16 port)
{
    if(Server->listen(QHostAddress(ipAddress), port))
        emit ListenStarted();
}

//关闭监听
void TCP_Server::StopListen()
{
    KickClient("All");
    Server->close();
}
//主动断开客户端连接
void TCP_Server::KickClient(QString ip)
{
    if(ip.contains("All"))
    {
        for(auto s : MyClients.values())
        {
            //收到客户端消息时
            disconnect(s,&QTcpSocket::readyRead,this,&TCP_Server::ReciveClientMessage);
            //客户端断开时
            disconnect(s,&QTcpSocket::disconnected,this,&TCP_Server::HasClientDisconnect);
            s->abort();
        }
    }
    else if(MyClients.contains(ip))
    {
        MyClients.value(ip)->abort();
    }
}

void TCP_Server::SendMessage(const QString ip, const QByteArray msg)
{
    MyClients.value(ip)->write(msg);
}

//有tcp客户端接入server时，在接收区提示
void TCP_Server::HasClientConnect()
{
    QTcpSocket* newClient = Server->nextPendingConnection();

    //新加入客户端的ip地址和端口号
    QString ClientIP = newClient->peerAddress().toString();
    ClientIP = ClientIP.mid(ClientIP.lastIndexOf(":")+1) + ":" + QString::number(newClient->peerPort());
    //收到客户端消息时
    connect(newClient,&QTcpSocket::readyRead,this,&TCP_Server::ReciveClientMessage, Qt::DirectConnection);
    //客户端断开时
    connect(newClient,&QTcpSocket::disconnected,this,&TCP_Server::HasClientDisconnect, Qt::DirectConnection);

    //主窗口显示有新客户端加入
    emit TcpServerMsgToUI("New Client:" + ClientIP + " connected!");
    emit UpdateClientsToUI("join",ClientIP);

    MyClients.insert(ClientIP,newClient);
    DEBUGinfo<<"现在有"<<MyClients.size()<<"个客户端";
}
//有客户端断开连接时，在接收区提示
void TCP_Server::HasClientDisconnect()
{
    QTcpSocket *sock = (QTcpSocket *)sender();
    QString ClientIP = sock->peerAddress().toString();
    ClientIP = ClientIP.mid(ClientIP.lastIndexOf(":")+1) + ":" + QString::number(sock->peerPort());
    MyClients.remove(ClientIP);
    //主窗口显示有客户端断开
    emit TcpServerMsgToUI("Client:" + ClientIP + " left!");
    emit UpdateClientsToUI("leave",ClientIP);
}

//接收消息
void TCP_Server::ReciveClientMessage()
{
    QTcpSocket *sock = (QTcpSocket *)sender();
    QByteArray msg = sock->readAll();
    emit ClientsMsgToUI(msg);
}
